package com.syqc.videos

import android.Manifest
import android.view.View
import android.widget.SeekBar
import android.widget.TextView
import androidx.core.view.isGone
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import autodispose2.autoDispose
import com.permissionx.guolindev.PermissionX
import com.syqc.comlib.UserConstant
import com.syqc.comlib.base.LazyLoadSirFragment
import com.syqc.comlib.callback.EmptyCallback
import com.syqc.comlib.rx.LiveDataBus
import com.syqc.comlib.rx.filterFast
import com.syqc.comlib.utils.startActivityTo
import com.syqc.comlib.utils.toast
import com.syqc.interfaces.SimpleSeekBarChangeListener
import com.syqc.monitor.R
import com.syqc.monitor.databinding.FragmentRealVideoBinding
import com.syqc.monitor.popup.PopupActivity
import com.syqc.utils.Keys
import com.syqc.utils.ToolsUtil
import com.syqc.videos.videomanager.PlayerManager
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers

class RealPlayerFragment :
    LazyLoadSirFragment<FragmentRealVideoBinding>(FragmentRealVideoBinding::inflate) {
    //是否开始录音
    private var isRecord = true

    private val mViewModel by viewModels<RealPlayerVM>()
    private var mAdapter: RealPlayerAdapter? = null
    private val mActivityVM by activityViewModels<CarMonitorViewModel>()
    private var isFirst = true
    override fun initView(view: View) {
        initRecycler()
        initViewModel()
        handAudio()
    }

    override fun initData() {
        mActivityVM.carId.observe(this) { mViewModel.carId = it }
        mActivityVM.videos.observe(this) {
            mAdapter?.setList(null)
            mViewModel.clearMap()
            binding.llControl.isVisible = false
            binding.llControl.isEnabled = true
            binding.llRealVideoTalk.isEnabled = true
            binding.llRealVideoInfo.isEnabled = true

            if (it.isNullOrEmpty()) {
                loadService.setCallBack(EmptyCallback::class.java) { context, view ->
                    val empty = view.findViewById<TextView>(R.id.tv_empty)
                    empty.text = getString(R.string.desc_choose_not_video_car)
                }
                loadService.showCallback(EmptyCallback::class.java)
            } else {
                if (isFirst) {
                    isFirst = false
                    isShowLoading(true)
                    binding.llControl.postDelayed({
                        isShowLoading(false)
                        handVideos(it)
                    }, 2000)
                } else {
                    handVideos(it)
                }
            }
        }
        if (mViewModel.carId.isEmpty()) {
            loadService.setCallBack(EmptyCallback::class.java) { context, view ->
                val empty = view.findViewById<TextView>(R.id.tv_empty)
                empty.text = getString(R.string.hint_toast_choose_car)
            }
            loadService.showCallback(EmptyCallback::class.java)
        }
    }

    private fun handVideos(it: String?) {
        mAdapter?.carId = mViewModel.carId
        binding.root.postDelayed({
            mViewModel.isClient(it)
            loadService.showSuccess()
        }, 100)

    }

    private fun initViewModel() {
        mViewModel.toastObserver().observeOn(AndroidSchedulers.mainThread())
            .autoDispose(scopeProvider).subscribe(this::toastObserver)
        mViewModel.passLive.observe(this) {
            mAdapter?.setList(it)
            if (it.isNullOrEmpty()) {
                loadService.showCallback(EmptyCallback::class.java)
            } else {
                loadService.showSuccess()
            }
        }
        mViewModel.actionLive.observe(this) {
            val action = mViewModel.getAction()
            binding.ivLight.isSelected = action.light == 1
            binding.ivWiper.isSelected = action.wiper == 1
            binding.ivWiperO.isSelected = action.wiper == 1
        }

        //切换通道监听
        LiveDataBus.get().with("RealPass", String::class.java).observe(this) {
            mViewModel.controlPass = it
            mViewModel.setAudioPass(it)
            val action = mViewModel.getAction()
            binding.ivLight.isSelected = action.light == 1
            binding.ivWiper.isSelected = action.wiper == 1
            binding.ivWiperO.isSelected = action.wiper == 1
        }
    }


    override fun initEvent() {

        binding.llRealVideoInfo.filterFast {
            if (mViewModel.carId.isEmpty()) {
                R.string.hint_toast_choose_car.toast(requireContext())
                return@filterFast
            }
            startActivityTo<PopupActivity>(requireContext()) {
                putExtra(Keys.INTENT_CAR_ID, mViewModel.carId)
            }
        }
        binding.llRealVideoTalk.setOnClickListener {
            if (mViewModel.isParamsOk()) return@setOnClickListener
            if (mViewModel.getAudioPass().isEmpty()) return@setOnClickListener
            if (isRecord) {
                isRecord = false
                binding.ivAudio.setImageResource(TalkHelper.voiceImg[0])
                getPermissions()
            } else {
                isRecord = true
                binding.ivAudio.setImageResource(TalkHelper.voiceImg[0])
                TalkbackUtil.closeTalk()
                binding.llRealVideoInfo.isEnabled = true
                binding.lltvControl.isEnabled = true
            }
        }

        binding.lltvControl.setOnClickListener {
            if (mViewModel.isParamsOk()) return@setOnClickListener
            val visible = binding.llControl.isVisible
            binding.llRealVideoInfo.isEnabled = visible
            binding.llRealVideoTalk.isEnabled = visible

            binding.llControl.isVisible = !visible
            binding.tvControl.isSelected = !visible
            binding.ivControl.isSelected = !visible

            val action = mViewModel.getAction()
            binding.ivLight.isSelected = action.light == 1
            binding.ivWiper.isSelected = action.wiper == 1
            binding.ivWiperO.isSelected = action.wiper == 1
            binding.llAperture.isInvisible = mViewModel.is28181
            binding.llFocal.isGone = mViewModel.is28181
            binding.llWiper.isInvisible = mViewModel.is28181
            binding.llWiperO.isVisible = mViewModel.is28181

        }

        binding.vUp.setOnClickListener { mViewModel.control(1) }
        binding.vLeft.setOnClickListener { mViewModel.control(3) }
        binding.vCenter.setOnClickListener { mViewModel.control(0) }
        binding.vRight.setOnClickListener { mViewModel.control(4) }
        binding.vDown.setOnClickListener { mViewModel.control(2) }



        binding.ivFocalUp.setOnClickListener {
            mViewModel.changeAction(1, 0)
        }
        binding.ivFocalDown.setOnClickListener {
            mViewModel.changeAction(1, 1)
        }
        binding.ivApertureUp.setOnClickListener {
            mViewModel.changeAction(2, 0)
        }
        binding.ivApertureDown.setOnClickListener {
            mViewModel.changeAction(2, 1)
        }
        binding.ivZoomUp.setOnClickListener {
            mViewModel.changeAction(5, 0)
        }
        binding.ivZoomDown.setOnClickListener {
            mViewModel.changeAction(5, 1)
        }

        binding.ivLight.setOnClickListener {
            val light = mViewModel.getAction().light
            if (light == 0) {
                mViewModel.changeAction(4, 1)
            } else {
                mViewModel.changeAction(4, 0)
            }
        }
        binding.ivWiperO.setOnClickListener {
            val wiper = mViewModel.getAction().wiper
            if (wiper == 0) {
                mViewModel.changeAction(3, 1)
            } else {
                mViewModel.changeAction(3, 0)
            }
        }
        binding.ivWiper.setOnClickListener {
            val wiper = mViewModel.getAction().wiper
            if (wiper == 0) {
                mViewModel.changeAction(3, 1)
            } else {
                mViewModel.changeAction(3, 0)
            }
        }

        binding.sbSpeed.setOnSeekBarChangeListener(object : SimpleSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                super.onProgressChanged(seekBar, progress, fromUser)
                mViewModel.speed = seekBar?.progress ?: 0
                binding.tvSpeedNum.text = mViewModel.speed.toString()
            }
        })

    }

    private fun initRecycler() {
        binding.recyclerVideo.layoutManager = GridLayoutManager(requireContext(), 2)
        mAdapter = RealPlayerAdapter(UserConstant.current_userId)
        binding.recyclerVideo.adapter = mAdapter
    }

    //重置车辆相关内容
    fun resetCar() {
        mAdapter?.clearPlayer()
        PlayerManager.clearAllVideo()
        isRecord = true
        TalkbackUtil.closeTalk()
    }

    private fun clearPlayers() {
        mAdapter?.clearPlayer()
    }

    //////////////////////////////////////////////////////////////////////////////////////////////
    private fun getPermissions() {
        PermissionX.init(requireActivity()).permissions(
            Manifest.permission.RECORD_AUDIO
        ).request { allGranted, grantedList, deniedList ->
            if (allGranted) {
                binding.llRealVideoInfo.isEnabled = false
                binding.lltvControl.isEnabled = false
                binding.tvRealVideoTalk.isSelected = true
                binding.ivRealVideoTalk.isSelected = true
                binding.tvRealVideoTalk.setText(R.string.desc_video_car_talk_close)
                TalkbackUtil.openTalk(
                    requireContext(),
                    mViewModel.carId,
                    mViewModel.getAudioPass()
                )
            } else {
                binding.llRealVideoInfo.isEnabled = true
                binding.lltvControl.isEnabled = true
                getString(
                    R.string.toast_persission_open,
                    getString(R.string.permission_audio)
                ).toast(requireContext())
            }
        }
    }

    private var isBackground = false

    override fun onPause() {
        super.onPause()
        if (mAdapter != null) {
            isBackground = false
            if (!ToolsUtil.isAppOnForeground(requireContext())) {
                isBackground = true
                TalkbackUtil.getPlayer()?.let {
                    PlayerManager.clearAllNorAudio(it.getKey())
                }
                clearPlayers()
            }
        }
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (hidden) {
            clearPlayers()
            PlayerManager.clearAllVideo()
        } else {
            mViewModel.handlePass()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        PlayerManager.clearAllVideo()
        TalkbackUtil.destroy()
    }

    fun onKeyDown(): Boolean {
        return if (isAdded)
            PlayerManager.backFromWindowFull(requireContext(), mAdapter?.getFullKey() ?: "")
        else false
    }
    //////////////////////////////////////////////对讲/////////////////////////////////////////////////

    private fun handAudio() {
        TalkbackUtil.status.autoDispose(scopeProvider).subscribe {
            when (it) {
                TalkStatus.CLOSE -> {
                    binding.tvAudio.setText(R.string.toast_audio_close)
                    closeAudioVideo()

                }

                TalkStatus.OPEN -> {
                    binding.llAudio.isVisible = true
                    binding.tvAudio.setText(R.string.toast_audio_link)
                }

                TalkStatus.SUCCESS -> {
                    binding.tvAudio.setText(R.string.toast_audio_talking)
                }

                TalkStatus.FAILURE -> {
                    binding.tvAudio.text = TalkbackUtil.toast
                    binding.tvAudio.postDelayed({
                        closeAudioVideo()
                    }, 3000)
                }

                else -> {}
            }
        }
        //上传PCM数据网络失败监听
        TalkbackUtil.upload.autoDispose(scopeProvider).subscribe {
            isRecord = true
            TalkbackUtil.closeTalk()
            binding.llRealVideoInfo.isEnabled = true
            binding.lltvControl.isEnabled = true
            binding.llAudio.isVisible = false
        }
        TalkbackUtil.image.autoDispose(scopeProvider).subscribe {
            binding.ivAudio.setImageResource(it)
        }
        TalkbackUtil.toastLive.observeOn(AndroidSchedulers.mainThread()).autoDispose(scopeProvider)
            .subscribe {
                showToast(it)
            }
    }

    private fun closeAudioVideo() {
        isRecord = true
        binding.tvRealVideoTalk.isSelected = false
        binding.llAudio.isVisible = false
        binding.tvRealVideoTalk.setText(R.string.desc_video_car_talk_open)
        binding.ivRealVideoTalk.isSelected = false
        binding.llRealVideoInfo.isEnabled = true
        binding.lltvControl.isEnabled = true
    }
}